import axios from 'axios'
import Cookie from 'js-cookie'
import store from '../store'

// 跨域认证信息 header 名
// const xsrfHeaderName = 'Authorization'
axios.defaults.timeout = 50000
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
// axios.defaults.withCredentials= true
// axios.defaults.xsrfHeaderName= xsrfHeaderName
// axios.defaults.xsrfCookieName= xsrfHeaderName
// axios.defaults.headers.common['Authorization'] = store.getters['account/jwt']

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(url, method, config = {}) {
  return axios.request({
    url: url,
    method: method,
    ...config
  })
}

/**
 * 设置认证信息
 * @param auth {Object}
 *
 */
function setAuthorization(auth) {
  // switch (authType) {
  //   case AUTH_TYPE.BEARER:
  //     Cookie.set(xsrfHeaderName, 'Bearer ' + auth.token, {expires: auth.expireAt})
  //     break
  //   case AUTH_TYPE.BASIC:
  //   case AUTH_TYPE.AUTH1:
  //   case AUTH_TYPE.AUTH2:
  //   default:
  //     break
  // }
  store.commit('account/setJwt', auth)
}

/**
 * 移出认证信息
 *
 */
function removeAuthorization() {
  // switch (authType) {
  //   case AUTH_TYPE.BEARER:
  //     Cookie.remove(xsrfHeaderName)
  //     break
  //   case AUTH_TYPE.BASIC:
  //   case AUTH_TYPE.AUTH1:
  //   case AUTH_TYPE.AUTH2:
  //   default:
  //     break
  // }
  store.commit('account/setJwt', null)
}

/**
 * 检查认证信息
 * @param authType
 * @returns {boolean}
 */
function checkAuthorization() {
  // switch (authType) {
  //   case AUTH_TYPE.BEARER:
  //     if (Cookie.get(xsrfHeaderName)) {
  //       return true
  //     }
  //     break
  //   case AUTH_TYPE.BASIC:
  //   case AUTH_TYPE.AUTH1:
  //   case AUTH_TYPE.AUTH2:
  //   default:
  //     break
  // }
  if (store.getters['account/jwt']) {
    store.commit('account/setJwt', store.getters['account/jwt'])
  }
  return !!store.state.account.jwt
}

/**
 * 加载 axios 拦截器
 * @param interceptors
 * @param options
 */
function loadInterceptors(interceptors, options) {
  const { request, response } = interceptors
  // 加载请求拦截器
  request.forEach(item => {
    let { onFulfilled, onRejected } = item
    if (!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = config => config
    }
    if (!onRejected || typeof onRejected !== 'function') {
      onRejected = error => Promise.reject(error)
    }
    axios.interceptors.request.use(
      config => onFulfilled(config, options),
      error => onRejected(error, options)
    )
  })
  // 加载响应拦截器
  response.forEach(item => {
    let { onFulfilled, onRejected } = item
    if (!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = response => response
    }
    if (!onRejected || typeof onRejected !== 'function') {
      onRejected = error => Promise.reject(error)
    }
    axios.interceptors.response.use(
      response => onFulfilled(response, options),
      error => onRejected(error, options)
    )
  })
}

/**
 * 解析 url 中的参数
 * @param url
 * @returns {Object}
 */
function parseUrlParams(url) {
  const params = {}
  if (!url || url === '' || typeof url !== 'string') {
    return params
  }
  const paramsStr = url.split('?')[1]
  if (!paramsStr) {
    return params
  }
  const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ')
  for (let i = 0; i < paramsArr.length / 2; i++) {
    const value = paramsArr[i * 2 + 1]
    params[paramsArr[i * 2]] = value === 'true' ? true : value === 'false' ? false : value
  }
  return params
}

export { request, setAuthorization, removeAuthorization, checkAuthorization, loadInterceptors, parseUrlParams }
